/**
 * TODO Write Javadoc for FeedActivity
 * @author cathbar
 */
package com.dylankenny.flikrreader.android;

import java.util.ArrayList;
import java.util.Arrays;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.GridView;

import com.dylankenny.flikrreader.R;
import com.dylankenny.flikrreader.model.data.Feed;
import com.dylankenny.flikrreader.model.data.FeedItem;
import com.dylankenny.flikrreader.model.parse.JsonFeedCodec;
import com.dylankenny.flikrreader.model.parse.NetworkListener;
import com.dylankenny.flikrreader.model.parse.NetworkManager;
import com.dylankenny.flikrreader.model.parse.XMLReader;
import com.dylankenny.flikrreader.view.FeedItemAdapter;

/**
 * @author cathbar
 */
public class FeedActivity extends Activity implements NetworkListener {
	FeedItemAdapter feedItemAdapter;

	ArrayList<FeedItem> feedItems;

	private String url;

	enum Format {
		JSON, XML;
	}

	private Format format;

	private ShakeListener shakeListener;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_feed);
		Intent intent = this.getIntent();
		this.url = intent.getStringExtra(MainActivity.getUrlKey());
		if (this.url.endsWith("json")) {
			this.format = Format.JSON;
		} else {
			this.format = Format.XML;
		}
		this.feedItems = new ArrayList<FeedItem>();
		this.initializeShaker(this.shakeListener);
		this.updateList(true);
	}

	/**
	 * Update the list of items
	 * 
	 * @author cathbar
	 */
	private void updateList(boolean keepOldImages) {
		if (!keepOldImages)
			this.feedItems.clear();
		new LongOperation().execute(this.url);
		this.initializeGridView(this.feedItems);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		this.getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/**
	 * Set up the griv view
	 * 
	 * @author cathbar
	 * @param feedItems
	 */
	private void initializeGridView(ArrayList<FeedItem> feedItems) {
		this.feedItemAdapter = new FeedItemAdapter(this, android.R.layout.simple_gallery_item, feedItems);
		GridView photoGrid = (GridView) this.findViewById(R.id.photo_grid);
		photoGrid.setAdapter(this.feedItemAdapter);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.dylankenny.flikrreader.model.parse.NetworkListener#onFeedItemDownloaded
	 * (com.dylankenny.flikrreader.model.data.FeedItem)
	 */
	@Override
	public void onFeedItemDownloaded(FeedItem feedItem) {
		this.feedItemAdapter.notifyDataSetChanged();
	}

	private class LongOperation extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {

			return NetworkManager.DownloadFromUrlToString(params[0]);
		}

		@Override
		protected void onPostExecute(String result) {
			String feedString = result;

			// flickr's json is encapsulated with jsonFlikrFeed(), rather than
			// just starting with {... Gonna strip that...
			Feed feed = null;
			switch (FeedActivity.this.format) {
			case XML:
				feed = this.parseXML(feedString);
				break;
			case JSON:
				feed = this.parseJson(feedString);
				break;
			}
			FeedActivity.this.feedItemAdapter.addAll(Arrays.asList(feed.getItems()));
			FeedActivity.this.feedItemAdapter.notifyDataSetChanged();

		}

		/**
		 * Parse the feed string into a Feed. This is for an xml string.
		 * 
		 * @author cathbar
		 * @param feedString
		 * @return
		 */
		private Feed parseXML(String feedString) {
			Feed feed = null;
			feed = XMLReader.parseXML(feedString);
			return feed;
		}

		/**
		 * Parse the feed string into a Feed. This is for an json string.
		 * 
		 * @author cathbar
		 * @param feedString
		 * @return
		 */
		public Feed parseJson(String feedString) {
			// The json is formed strangly, an is wrapped in a jsonFlikrFeed. I
			// strip it.
			feedString = feedString.replace("jsonFlickrFeed(", "");
			feedString = new StringBuilder(feedString).replace(feedString.lastIndexOf(")"), feedString.lastIndexOf(")") + 1, "").toString();
			Feed feed = JsonFeedCodec.deserializeFeed(feedString);
			return feed;
		}

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}

	/**
	 * Initialize the shake listener
	 * 
	 * @author cathbar
	 * @param shakeListener
	 */
	private void initializeShaker(ShakeListener shakeListener) {
		shakeListener = new ShakeListener(this);
		shakeListener.setOnShakeListener(new ShakeListener.OnShakeListener() {
			@Override
			public void onShake() {
				new AlertDialog.Builder(FeedActivity.this).setPositiveButton("Keep old ones", new OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						FeedActivity.this.updateList(true);
					}

				}).setNegativeButton("Delete old ones", new OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						FeedActivity.this.updateList(false);
					}

				}).setTitle("Refresh").setMessage("Delete old images or just add new ones?").show();

			}
		});
	}

}
